<?php

namespace admin\widgets;

use app\models\OrderLog;
use yii\base\Widget;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;

class OrderLogWidget extends Widget {

    public $order_id;
    public $options = ['class' => 'table'];
    public $template = '<tr><td class="text-left">{value}</td></tr>';
    public $before = '<tr><th class="text-left">{title}</th></tr>';
    public $title = '订单日志';

    public function run() {
        $models = OrderLog::find()->where(['order_id' => $this->order_id])
            ->orderBy('id desc')
            ->asArray()
            ->all();

        $rows = [];
        if (!empty($this->title)) {
            $rows[] = str_replace('{title}', $this->title, $this->before);
        }
        foreach ($models as $model) {
            $rows[] = $this->renderItem($model);
        }

        $options = $this->options;
        $tag = ArrayHelper::remove($options, 'tag', 'table');

        return Html::tag($tag, implode("\n", $rows), $options);
    }

    private function renderItem($model) {
        return strtr($this->template, [
            '{value}' => date('Y-m-d H:i:s', $model['ctime']) . "\t{$model['content']}",
        ]);
    }
}